<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="data" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="供应商昵称" prop="vendor_name" style="margin-bottom: 30px;">
                    <el-input v-model="data.vendor_name" placeholder="供应商昵称" />
                </el-form-item>
                        <el-form-item label="供应商编码" style="margin-bottom: 30px;">
                            <el-input v-model="data.vendor_code" placeholder="不输入则自动获取编号" />
                        </el-form-item>
                        <el-form-item label="签约开始时间" prop="vendor_starttime" style="margin-bottom: 30px;">
                            <el-date-picker v-model="data.vendor_starttime" type="date" style="width: 460px;" placeholder="签约开始时间" :size="size" />
                        </el-form-item>
                        <el-form-item label="结算期限" prop="vendor_term" style="margin-bottom: 30px;">
                            <el-select v-model="data.vendor_term" placeholder="请选择供应商分类">
                                <el-option v-for="item in vendorqx" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="vendor_address" label="供应商地址" style="margin-bottom: 30px;">
                            <el-input v-model="data.vendor_address" placeholder="供应商地址" />
                        </el-form-item>
                        <el-form-item label="负责人部门" prop="vendor_depd_id" style="margin-bottom: 30px;">
                                <el-tree-select v-model="data.vendor_depd_id" :data="deptOptions" :props="defaultProps"
                                :check-strictly="true" placeholder="请选择销售部门" />
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="供应商分类" prop="vendor_classify" style="margin-bottom: 30px;">
                            <el-select v-model="data.vendor_classify" placeholder="请选择供应商分类">
                                <el-option v-for="item in vendorfl" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="客户等级" prop="vendor_grade" style="margin-bottom: 30px;">
                            <el-rate v-model="data.vendor_grade" :colors="colors" />
                        </el-form-item>
                        <el-form-item prop="vendor_endtime" label="签约结束时间" style="margin-bottom: 30px;">
                            <el-date-picker v-model="data.vendor_endtime" type="date" style="width: 460px;" placeholder="签约结束时间" :size="size" />
                        </el-form-item>
                        <el-form-item prop="vendor_rep_id" label="负责人姓名" style="margin-bottom: 30px;">
                            <!-- <el-input v-model="data.vendor_rep_id" placeholder="负责人姓名" /> -->
                            <el-select v-model="data.vendor_rep_id" placeholder="请选择负责人姓名">
                                <el-option v-for="item in userOptions" :key="item.user_id" :label="item.user_name"
                                    :value="item.user_id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="vendor_phone" label="负责人电话" style="margin-bottom: 30px;">
                            <el-input v-model="data.vendor_phone" placeholder="负责人电话" />
                        </el-form-item>
                        <el-form-item prop="dept_id" label="备注" style="margin-bottom: 30px;">
                            <el-input v-model="data.remark" placeholder="备注" type="textarea" clearable style="width: 100%;" />
                        </el-form-item>
                    </div>
                    
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">联系人信息</h2>
            <el-form ref="ruleFormRef1" style="max-width: 1200px;margin: 20px;" :model="data" status-icon
                :rules="rules1" label-width="auto" class="demo-ruleForm">
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item prop="contacts_name" label="联系人姓名" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_name" placeholder="联系人姓名" />
                        </el-form-item>
                        <el-form-item label="联系人手机号" prop="contacts_phone" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_phone" placeholder="联系人手机号" />
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="联系人职位" prop="contacts_posts" style="margin-bottom: 30px;">
                            <el-input v-model="data.contacts_posts" placeholder="联系人职位" />
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>
        <!-- 底部操作按钮 -->
        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="indexUpdate()">修改</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRoute,useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex'
export default {
    setup() {
        const store = useStore()
        const datamax = store.state.PO_UpdeteArray

        const Router = useRouter();
        const route = useRoute(); // 使用 useRoute 获取当前路由信息
        // const datas = JSON.parse(String(route.query.rowData));
        const data = reactive({
            vendor_name :"", //供应商昵称
            vendor_code :"",//供应商编码
            vendor_classify :"",//供应商分类
            vendor_grade :"", //供应商等级
            vendor_starttime :"", //签约开始时间
            vendor_endtime :"", //签约结束时间
            vendor_term :"", //结算期限
            vendor_address :"", //供应商地址
            vendor_rep_id :"", //负责人
            vendor_depd_id :"", //负责人所属部门
            vendor_phone :"", //联系电话
            contacts_name :"", //供应商联系人姓名
            contacts_phone :"", //供应商联系人电话
            contacts_posts :"", //联系人职位
            remark :"", //备注
            update_by: localStorage.getItem('userLName'),
            update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
            del_flag :"0" //逻辑删除
        })
        const vendorfl = ref([]);//供应商分类
        const vendorqx = ref([]);//供应商结算期限
        const userOptions = ref([]);//负责人
        const deptOptions = ref([]);//负责人所属部门
        const ruleFormRef = ref(null);
        const ruleFormRef1 = ref(null);
        const rules = reactive({
            vendor_name: [
                { required: true, message: "供应商名称不能为空", trigger: "blur" },
            ],
            vendor_code: [
                { required: true, message: "供应商编码不能为空", trigger: "blur" },
            ],
            vendor_classify: [
                { required: true, message: "供应商分类", trigger: "blur" },
            ],
            vendor_grade: [
                { required: true, message: "供应商等级不能为空", trigger: "blur" },
            ],
            vendor_starttime: [
                { required: true, message: "签约开始时间不能为空", trigger: "blur" },
            ],
            vendor_endtime: [
                { required: true, message: "签约结束时间不能为空", trigger: "blur" },
            ],
            vendor_term: [
                { required: true, message: "结算期限不能为空", trigger: "blur" },
            ],
            vendor_address: [
                { required: true, message: "供应商地址不能为空", trigger: "blur" },
            ],
            vendor_rep_id: [
                { required: true, message: "负责人不能为空", trigger: "blur" },
            ],
            vendor_depd_id: [
                { required: true, message: "负责人所属部门不能为空", trigger: "blur" },
            ],
            vendor_phone: [
                { required: true, message: "负责人电话不能为空", trigger: "blur" },
            ],
            remark: [
                { required: true, message: "备注不能为空", trigger: "blur" },
            ]
        });
        const rules1 = reactive({
            contacts_name: [
                { required: true, message: "联系人姓名不能为空", trigger: "blur" },
            ],
            contacts_phone: [
                { required: true, message: "联系人电话不能为空", trigger: "blur" },
            ],
            contacts_posts: [
                { required: true, message: "联系人职位", trigger: "blur" },
            ],
        })
        onMounted(() => {
            getClassify()
            getSettlement()
            handleUpdateFZ()
            getUser()
            getDept()
        })
        //供应商分类
        function getClassify() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "Customer_classify"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                vendorfl.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }
        //供应商结算期限
        function getSettlement() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "settlement_period"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                vendorqx.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }
        //获取用户
        function getUser() {
            // console.log("获取用户")
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }
        //获取部门
        function getDept() {
            // console.log("获取部门")
            axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                
                deptOptions.value = convertToTreeOptions(result.data)
                
            }).catch((err) => {
                console.info(err)
            });
        }

        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.dept_id,
                label: item.dept_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }
        //非空验证
        async function indexUpdate() {
            console.log("进来了");
            // console.log(vendor_id)
            if (!ruleFormRef.value || !ruleFormRef1.value) {
                console.error('表单实例未正确绑定');
                return;
            }
            try {
                const ruleForm = await ruleFormRef.value.validate();
                const ruleForm1 = await ruleFormRef1.value.validate();
                if (ruleForm && ruleForm1) {
                    handleAdd();
                } else {
                    ElMessage({
                        type: 'error',
                        message: '请填写完整信息',
                    });
                }
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: '请填写完整信息',
                });
            }
        }
        //添加操作
        function handleAdd() {
            // console.log("id:"+data.vendor_id)
            // console.log("code:"+data.vendor_code)
            // console.log("name:"+data.vendor_name)
            // console.log("分类:"+data.vendor_classify)
            // console.log("等级:"+data.vendor_grade)
            // console.log("开始时间:"+data.vendor_starttime)
            // console.log("结束:"+data.vendor_endtime)
            // console.log("地址:"+data.vendor_address)
            // console.log("userid:"+data.vendor_rep_id)
            // console.log("部门:"+data.vendor_depd_id)
            // console.log("电话:"+data.vendor_phone)
            // console.log("联系人姓名:"+data.contacts_name)
            // console.log("联系人电话:"+data.contacts_phone)
            // console.log("联系人职位:"+data.contacts_posts)
            // console.log("备注:"+data.remark)
            // console.log("创建人:"+data.create_by)
            // console.log("创建时间:"+data.create_time)
            // console.log("期限"+data.vendor_term)
            axios.put('http://localhost:5181/api/Values/Pinv_VendorUpdate',{
                vendor_id:data.vendor_id,
                vendor_name:data.vendor_name,
                vendor_classify:data.vendor_classify,
                vendor_grade:data.vendor_grade,
                vendor_starttime:data.vendor_starttime,
                vendor_endtime:data.vendor_endtime,
                vendor_term:data.vendor_term,
                vendor_address:data.vendor_address,
                vendor_rep_id:data.vendor_rep_id,
                vendor_depd_id:data.vendor_depd_id,
                vendor_phone:data.vendor_phone,
                contacts_name:data.contacts_name,
                contacts_phone:data.contacts_phone,
                contacts_posts:data.contacts_posts,
                remark:data.remark,
                update_by: localStorage.getItem('userLName'),
                update_time:data.create_time
            },{ headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`
            } }).then((result) => {
                // console.log(result)  // 打印响应数据
                if (result.data>0) {
                    ElMessage({
                        type: 'success',
                        message: '修改成功',
                    });
                    Router.push({
                        path: '/main/Pinv/vendor',
                    });
                } else {
                    ElMessage({
                        type: 'error',
                        message: '修改失败',
                    });
                }
            })
        }
        //修改操作
        function handleUpdateFZ() {
            data.vendor_id = datamax.vendor_id
            data.vendor_code = datamax.vendor_code
            data.vendor_name = datamax.vendor_name
            data.vendor_classify = String(datamax.vendor_classify)
            data.vendor_grade = datamax.vendor_grade
            data.vendor_starttime = new Date(datamax.vendor_starttime).toISOString()//转换时间格式
            data.vendor_endtime = new Date(datamax.vendor_endtime).toISOString()//转换时间格式
            data.vendor_term = datamax.vendor_term
            data.vendor_address = datamax.vendor_address
            data.vendor_rep_id = datamax.vendor_rep_id
            data.vendor_depd_id = datamax.vendor_depd_id
            data.vendor_phone = datamax.vendor_phone
            data.contacts_name = datamax.contacts_name

            data.contacts_phone = datamax.contacts_phone
            data.contacts_posts = datamax.contacts_posts
            data.remark = datamax.remark
            data.create_by = datamax.create_by
            data.create_time = datamax.create_time
        }
        //返回上一级
        function handleClose(){
            // console.log("返回")
            Router.push({
                    path: '/main/Pinv/vendor',
                });
        }
            
        
        return {
            datamax,
            data,
            vendorqx,
            vendorfl,
            rules,
            rules1,
            ruleFormRef,
            userOptions,
            deptOptions,
            ruleFormRef1,
            handleClose,
            handleAdd,
            indexUpdate
        }

    }
}
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
    margin-top: -40px;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    margin-top: -20px;
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}
</style>